package database.example.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import java.util.Set;

/**
 * @author M201_06
 * 파일로 저장하기
 */
public class DbProperties {
		
		//불러오기
		public static Properties loadProperties(String propertiesFile){
			 BufferedInputStream bis = null;
			 Properties prop=null;
			try {
				bis = new BufferedInputStream(new FileInputStream(propertiesFile));
				prop = new Properties();
				prop.loadFromXML(bis); 
			} catch (FileNotFoundException e) {
				System.err.print("파일이 존재하지 않음");
			} catch (InvalidPropertiesFormatException e) {
				System.err.print("유효하지 않은 파일");
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(bis!=null)try {bis.close();} catch (IOException e) {bis=null;}
			}
			 return prop;
		}
		
		//saveProperties("test.prof", "user", "pass, "db);
		public static void saveProperties(String profertiesFile, String...value){
			BufferedOutputStream bos = null;
			Properties prop = null;
			try {
				bos = new BufferedOutputStream(new FileOutputStream(profertiesFile));
				prop = new Properties();
				//값 저장, 암호화 아리아
				prop.setProperty("DRIVER", value[0]);
				prop.setProperty("URL", value[1]);
				prop.setProperty("ID", value[2]);
				prop.setProperty("PASSWORD", value[3]);
				
				prop.storeToXML(bos, "DataBase connection XML Property File");
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			finally{
				if(bos!=null)try {bos.close();} catch (Exception e) {bos=null;}
			}		
	}
	
	public static void prnProperties(Properties prop){
		Set<Entry<Object,Object>> setmap = prop.entrySet();
		for(Entry<Object, Object> propty : setmap){
			System.out.printf("%s : %s\n",propty.getKey(),propty.getValue());
		}
	}
}
